# -*- coding: utf-8 -*-
import cookielib
import urllib
import urllib2
import socket
import os
import config

socket.setdefaulttimeout( 1200 )

def readHTML(url, post = 0):
	try:
		if not post:
		  handle = urllib2.urlopen(url)
		else:
		  handle = urllib2.urlopen(url, urllib.urlencode(post))		  
		  
		if not handle.info()['Content-Type'][:4] == 'text':
			return False
		html = handle.readlines()
		handle.close()
		html_strip = ""
		for line in html:
			html_strip = html_strip+line.strip("\r\n\t").strip()
		return html_strip
	except:
		return False
	
def getBetween(Text, String1, String2):
		if not Text:
			return False

		try:
			split1 = Text.split(String1, 1)[1]
			split2 = split1.split(String2, 1)[0]
			return urllib.unquote(split2)

		except:
			return False

class CookieStore:
	cookie = {}
	
	@staticmethod
	def get( section ):
		try:
			return CookieStore.cookie[ section ]
		except:
			return False
	
	@staticmethod
	def set( section, cookie ):
		CookieStore.cookie[ section ] = cookie

def getObj(url):
	print url.find( 'rapidshare.com' )
	if url.find( 'rapidshare.com' ) > 0:
		return Rapidshare( url )
	elif url.find( 'sendspace.pl' ) > 0:
		return SendSpace( url )
	else:
		return Plain( url )

class Plain:
	def __init__(self, url, parent = False):
		if not url.lower().startswith('http://'):
			url = 'http://' + url
		
		self.parent = parent
		self.url = url
		
	def getFileName(self):
		return os.path.basename( self.url )
		
	def getUrl(self):
		return self.url
		
	def getSleepTime(self):
		return 0
	
	def type(self):
		return 'plain'
		
class Rapidshare:
	def __init__(self, url, parent = False):
		if config.loadConf('rapidshare_username'):
			post = urllib.urlencode( {'uselandingpage' : 1, 'login' : config.loadConf('rapidshare_username'), 'password' : config.loadConf('rapidshare_password') } )
			handle = urllib2.urlopen( 'https://ssl.rapidshare.com/cgi-bin/premiumzone.cgi', post )
			CookieStore.set('rapidshare', handle.headers.get("set-cookie", "") )
		
		if not url.lower().startswith('http://'):
			url = 'http://' + url
		
		self.parent = parent
		self.url = url
		self.sleepTime = False
	
	def type(self):
		return 'rapidshare'
	
	def getFileName(self):
		return os.path.basename( self.url )
		
	def getUrl(self):
		if CookieStore.get('rapidshare'):
			self.sleepTime = 0
			return self.url
		else:
			content = readHTML( self.url )
			
			if not content:
				return False
				
			url = getBetween( content, '<form id="ff" action="', '" method="post">')
			
			if not url:
				return False
				
			content = readHTML( url, { 'dl.start' : 'Free' } )
			
			url = getBetween( content, "<input checked type=\"radio\" name=\"mirror\" onclick=\"document.dlf.action=\\'", "\\';\" />" )
			
			if not url:
				if getBetween( content, "You have ", " the download" ) == "reached":
					self.sleepTime = int( getBetween( content, "Or try again in about ", "minutes") )
					return 'wait'
				else:
					return False
			
			self.sleepTime = int( getBetween( content, 'var c=', ';' ) )
			
			return url

		
	def getSleepTime(self):
		return self.sleepTime

class SendSpace:
	def __init__(self, url, parent = False):
		self.url = url
		self.parent = parent
		
		if not url.lower().startswith('http://'):
			url = 'http://' + url
		
		self.parent = parent
		self.url = url
		self.sleepTime = False
	
	def type(self):
		return 'sendspace'
		
	def getFileName(self):
		content = readHTML( self.url )
		
		name = getBetween( content, '" class="violet" style="font-size: 14px;">', '</a>')
		
		if not name:
			return False
		else:
			return name
		
	def getUrl(self):
		content = readHTML( self.url )
		
		url = getBetween( content, 'Nazwa pliku:<br /><a href="', '" class="violet" style="font-size: 14px;">')
		
		if not url:
			return False
		else:
			return url
		
	def getSleepTime(self):
		return self.sleepTime
		